package com.nervenets.shopping.service.impl;

import com.nervenets.general.redis.RedisSyncLocker;
import com.nervenets.general.service.impl.BaseServiceImpl;
import com.nervenets.general.utils.JodaUtils;
import com.nervenets.shopping.hibernate.dao.DataOfWeekDao;
import com.nervenets.shopping.hibernate.domain.data.DataOfWeek;
import com.nervenets.shopping.service.DataOfWeekService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class DataOfWeekServiceImpl extends BaseServiceImpl<DataOfWeek, DataOfWeekDao> implements DataOfWeekService {
    @Resource
    private RedisSyncLocker<Void> redisSyncLocker;

    @Override
    public DataOfWeek checkAndGenerateData(long timestamp) {
        DataOfWeek dataOfWeek = dao.findByCreateTime(timestamp);
        if (null == dataOfWeek) {
            dataOfWeek = new DataOfWeek();
            dataOfWeek.setCreateTime(timestamp);
            save(dataOfWeek);
        }
        return dataOfWeek;
    }

    @SneakyThrows
    @Override
    public void updateData(long startOfWeekTime, long groupSuccessCount) {
        final long startOfThisWeek = JodaUtils.getStartOfThisWeek();
        redisSyncLocker.keyLock("DataOfWeek" + startOfThisWeek, () -> {
            DataOfWeek dataOfUser = checkAndGenerateData(startOfThisWeek);
            dataOfUser.setGroupSuccessCount(groupSuccessCount);
            save(dataOfUser);
            return null;
        });
    }
}
